package com.zzc.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;


@Component
public class UpLoad {

    @Value("${target.path}")
    private String targetPath;
    @Value("${picture.path}")
    private String picturePath;

    public String upload(MultipartFile file) throws IOException {

        String extName = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        //用UUID避免文件命名冲突
        String fileName = UUID.randomUUID().toString() + extName;

        FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(new File(targetPath + fileName)));
        FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(new File(picturePath + fileName)));
        return targetPath.substring(63) + fileName;
    }
}
